package com.longrise.android.widget;

import java.io.File;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.util.List;
import java.util.UUID;

import com.longrise.android.FrameworkManager;
import com.longrise.android.LDownloadFileProgressBaseView;
import com.longrise.android.LDownloadFileProgressHandler;
import com.longrise.android.LDownloadFileProgressManager;
import com.longrise.android.R;
import com.longrise.android.UIManager;
import com.longrise.android.database.LDBHelper;
import com.longrise.android.database.table.LDownloadFileProgressViewTable;
import com.longrise.android.widget.charts.LProgressView;
import com.longrise.ormlite.stmt.DeleteBuilder;
import com.longrise.ormlite.stmt.QueryBuilder;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils.TruncateAt;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;

public class LDownloadFileProgressView extends LDownloadFileProgressBaseView implements OnClickListener
{
	private Context _context = null;
	private String _name = null;
	private float _density = 1;
    private Paint _mPaint = null;
    private int _borderColor = Color.parseColor("#bfbfbf");  
    private TextView _title_tv = null;
    private TextView _speed_tv = null;
    private TextView _progress_tv = null;
    private LinearLayout _btn_body = null;
    private TextView _btn = null;
    private LProgressView _probar = null;
    private LinearLayout _delbtn_body = null;
    
    private boolean _isShowBorderLeft = false;
	private boolean _isShowBorderTop = false;
	private boolean _isShowBorderRight = false;
	private boolean _isShowBorderBottom = false;
    
    private String _url = null;
    private String _filepath = null;
    private String _filename = null;
    private String _clientName = null;
    private LDownloadFileProgressHandler _handler = null;
    private OutputStream _outputStream = null;
    
    private LFileOpenType _opentype = LFileOpenType.Default;
    private LFileOpenMode _openMode = LFileOpenMode.Normal;			//只前只用于wps
    private OnLDownloadFileProgressViewOpenFileListener _openfileLinstener = null;
    private OnLDownloadFileProgressViewDownloadFinishListener _downFinishListener = null;
    private OnLDownloadFileProgressViewDownloadErrorListener _downErrorListener = null;
    private OnLDownloadFileProgressViewStartListener _startLinstener = null;
    private OnLDownloadFileProgressViewDeleteListener _deleteLinstener = null;
    
    private boolean _enable = true;

	private int k = 0;
    
    public synchronized void setSpeed(String text)
    {
    	if(null!=this._speed_tv)
    	{
    		this._speed_tv.setText(text);
    	}
    }
    
    public String getName()
    {
    	return this._name;
    }
    
    public String getUrl()
    {
    	return this._url;
    }
    
    public void setClientName(String name)
    {
    	this._clientName = name;
    }
    
    public String getFilePath()
    {
    	if(null==this._filepath || "".equals(this._filepath))return null;
    	if(null==this._filename || "".equals(this._filename))return null;
    	return this._filepath+this._filename;
    }
	public String getClientName() 
	{		
		return this._clientName;
	}
    
	@Override
	public LDownloadFileProgressHandler getFileHandler() 
	{
		return this._handler;
	}

	@Override
	public OutputStream getOutputStream() 
	{
		return this._outputStream;
	}
    
    /**
     * 执行下载
     */
    public void start()
    {
    	try
    	{
    		if(!this._enable)return;
    		if(null==this._url || "".equals(this._url))return;    		
    		if(null==this._filepath || "".equals(this._filepath))return;
    		if(null==this._filename || "".equals(this._filename))return;
    		if(!this.checkSD())
    		{
    			Toast.makeText(this._context, "未检测到存储设备", Toast.LENGTH_SHORT).show();
    			return;
    		}
    		
    		if(LDownloadFileProgressManager.getInstance().startTask(this))
    		{
	    		if (null != _startLinstener)
	    		{
					_startLinstener.onLDownloadFileProgressViewStart(this, this._filepath+this._filename);
				}
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		
    	}
    }
   
    /**
     * 停止下载
     */
    public void stop()
    {
    	LDownloadFileProgressManager.getInstance().stopTask(this,0);//正常停止：0
    }
    
    
    /**
     * UI脱钩
     */
    public void tached()
    {
    	LDownloadFileProgressManager.getInstance().tached(this);
    }
    
    /**
     * UI脱钩
     */
    public void detached()
    {
    	LDownloadFileProgressManager.getInstance().detached(this);
    }
    
    /**
     * 删除
     */
    public void delete()
    {
    	LDownloadFileProgressManager.getInstance().stopTask(this, 6);//删除
    }
    
    /**
     * 是否下载完成
     * @return
     */
    public boolean isFinish()
    {
    	int progress = this.getProgress();
    	if(100==progress)
    	{
    		return true;
    	}
    	return false;
    }
    
    public boolean isRunning()
    {
    	return 1==this.getRunningStatus();
    }
    
    /**
     * 打开文件
     * 
     */
    public void open()
    {
    	File file = null;
		Intent intent = null;
		try
		{
			if(null==this._context)return;
			if(this.isFinish())
			{
				file = new File(this.getFilePath());
	            if(null!=file && file.exists() && file.isFile())
	            {
           	 		if(this._opentype == LFileOpenType.Default)
           	 		{
           	 			intent = this.getIntent(file);
           	 		}
           	 		else if(this._opentype == LFileOpenType.Wps)
           	 		{	           	 			
           	 			intent = this.getWpsFileIntent(file, this._openMode.name());
           	 		}
					if(null!=intent)
					{
						this._context.startActivity(intent);
					}
	           	 	
	            }
			}
		}
		catch(Exception ex)
		{}
		finally
		{
			file = null;
			intent = null;
		}
    }
    
    private void openfile()
    {
    	if(this._opentype != LFileOpenType.Never)
		{
			this.open();
		}
		if(null!=this._openfileLinstener)
		{
			this._openfileLinstener.onLDownloadFileProgressViewOpenFile(this, this._filepath+this._filename);
		}
    }
    
    private boolean checkSD()
	{
		if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
		{
			Toast.makeText(this._context, "未检测到SDCard", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}
    
    private int getProgress()
    {
    	File f = null;
    	QueryBuilder<LDownloadFileProgressViewTable,?> query = null;
    	List<LDownloadFileProgressViewTable> list = null;
    	int progress = 0;
    	String filepath = null;
		try
		{			
			if(null==this._context)return 0;
			filepath = getFilePath();
			if(null!=filepath && !"".equals(filepath) && null!=this._url && !"".equals(this._url))
			{
				f = new File(filepath);
				if(null!=f && f.exists())
				{
					query = LDBHelper.getQueryBuilder(this._context, LDownloadFileProgressViewTable.class);
					if(null!=query)
					{
						query.where().eq("filepath", filepath).and().eq("url", this._url);
						list = LDBHelper.query(this._context, LDownloadFileProgressViewTable.class, query.prepare());
						if(null!=list && 0<list.size())
						{
							progress = list.get(0).getProgress();
						}
					}
				}
			}
			if(0>=progress)
			{
				return 0;
			}
			else if(100<progress)
			{
				return 100;
			}
			return progress;
		}
		catch(Exception ex){}
		finally
		{
			query = null;
			list = null;
			f = null;
		}
    	return 0;
    }
    
    private void clean()
    {
    	if(null!=this._speed_tv)
		{
			this._speed_tv.setText("");
		}
		if(null!=this._progress_tv)
		{
			this._progress_tv.setText("");
		}
		if(null!=this._probar)
		{
			this._probar.setProgress(0);
		}
    }
 
    private void deleteCach()
    {
    	File f = null;
    	QueryBuilder<LDownloadFileProgressViewTable, ?> query = null;
    	try
    	{    		
    		if(null!=this._filepath && !"".equals(this._filepath)&&null!=this._filename && !"".equals(this._filename))
			{
				f = new File(this._filepath+this._filename);
				if(null!=f && f.exists())
				{
					f.delete();
				}
				query = LDBHelper.getQueryBuilder(this._context, LDownloadFileProgressViewTable.class);
				if(null!=query)
				{
					query.where().eq("filepath", this._filepath+this._filename).and().eq("url", this._url);
					LDBHelper.delete(this._context, LDownloadFileProgressViewTable.class, LDBHelper.query(this._context, LDownloadFileProgressViewTable.class, query.prepare()));
				}
			}
    		
    		if(null!=this._deleteLinstener)
    		{
    			this._deleteLinstener.onLDownloadFileProgressViewDelete();
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		f = null;
    		query = null;
    	}
    }
    
    public synchronized void updateProgress(int progress, long currentSize, String totalSize) 
	{
    	String fsize = null;
    	try
    	{
			if(progress < 0) 
	        {
				progress = 0;
	        }
	        else if(progress > 100) 
	        {
	        	progress = 100;
	        }
			if(null!=this._progress_tv)
    		{
    			this._progress_tv.setText(0<currentSize?(this.convertFileSize(currentSize)+"/"+totalSize):"");
    		}
			if(null!=this._probar && 0<=progress)
			{
				this._probar.setProgress(progress);					
			}
			if(100==progress)
			{
				fsize = getFileSize();
				if(null!=fsize)
				{
					if(null!=this._progress_tv)
		    		{
		    			this._progress_tv.setText(fsize);
		    		}
				}
			}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		
    	}
    }
    
    public synchronized void setStatus(int status)
    {
    	try
    	{ 
    		if(2==status)//下载完成
    		{
    			if(null!=this._downFinishListener)
				{
					this._downFinishListener.onLDownloadFileProgressViewDownloadFinish(this,this._filepath+this._filename);
				}
    		}
    		else if(3==status)
    		{
    			if(null!=this._downErrorListener)
    			{
    				this._downErrorListener.onLDownloadFileProgressViewDownloadError(this,this._filepath+this._filename);
    			}
    		}
    		else if(4==status)//等待下载
    		{
    			if(null!=this._progress_tv)
    			{
    				this._progress_tv.setText("等待中");
    			}
    			
    		}
    		else if(6==status)//删除
    		{
    			this.clean();
    			this.deleteCach();
    		}
    		else if(7==status)//清空
    		{
    			this.clean();
    		}
	    	if(null!=this._btn)
	    	{	    		
	    		if(0==status || 5==status || 6==status)
	    		{
	    			this._btn.setText("下载");	    			
	    		}
	    		else if(1==status)
	    		{
	    			this._btn.setText("暂停");
	    		}
	    		else if(2==status)
	    		{
	    			this._btn.setText("打开");
	    			
	    		}
	    		else if(3==status)
	    		{
	    			this._btn.setText("失败");
	    		}
	    		else if(4==status)
	    		{
	    			this._btn.setText("等待");
	    		}
	    	}
	    	
	    	
    	}
    	catch(Exception ex){}
    	finally
    	{
    		
    	}
    }
    
    private String getFileSize()
    {
    	String fpath = null;
    	File f = null;
    	try
    	{
    		fpath = this.getFilePath();
    		if(null!=fpath && !"".equals(fpath))
    		{
    			f = new File(fpath);
    			if(null!=f && f.exists() && f.isFile())
    			{
    				return this.convertFileSize(f.length());
    			}
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		f = null;
    	}
    	return null;
    }
    private String convertFileSize(long size) 
    {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
 
        if (size >= gb) 
        {
            return String.format("%.1f GB", (float) size / gb);
        } 
        else if (size >= mb) 
        {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } 
        else if (size >= kb) 
        {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        }
        else
        {
            return String.format("%d B", size);
        }
    }
    
    public void setDeleteButtonVisibility(int visibility)
    {
    	try
    	{
    		if(null!=this._delbtn_body)
    		{
    			this._delbtn_body.setVisibility(visibility);
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    	}
    }
    public void setControlButtonVisibility(int visibility)
    {
    	View v = null;
    	try
    	{
    		v = this.findViewById(k+1);
    		if(null!=v)
    		{
    			v.setVisibility(visibility);
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		v = null;
    	}
    }
    
    public void restProgress()
    {
    	LDownloadFileProgressManager.getInstance().addTask(this);
    }
    private void regEvent(boolean b)
    {
    	View v = null;
    	try
    	{
    		v = this.findViewById(k+1);
	    	if(null!=v)
	    	{
	    		v.setOnClickListener(b?this:null);
	    	}
	    	if(null!=this._delbtn_body)
	    	{
	    		this._delbtn_body.setOnClickListener(b?this:null);
	    	}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		
    	}
    }
    private void init()
    {
    	LayoutParams params = null;
    	LinearLayout left = null;
    		LinearLayout tip_body = null;
    	LinearLayout right = null;
    		
    			ImageView delbtn_iv = null;
    		
    	try
    	{	
    		this._density = FrameworkManager.getInstance().getDensity();
    		this._name = UUID.randomUUID().toString();
    		this.setBackgroundColor(Color.WHITE);
    		this.setOrientation(LinearLayout.HORIZONTAL);    		
    		this.setWillNotDraw(false);
    		
    		left = new LinearLayout(this._context);
    		if(null!=left)
    		{
    			params = new LayoutParams(0, LayoutParams.WRAP_CONTENT);//(int)(64*this._density)  LayoutParams.WRAP_CONTENT
    			if(null!=params)
    			{
    				params.weight = 1;
    				left.setLayoutParams(params);
    			}
    			left.setGravity(Gravity.CENTER_VERTICAL);
    			left.setOrientation(LinearLayout.VERTICAL );
    			
	    		this._title_tv = new TextView(this._context);
	    		if(null!=this._title_tv)
	    		{	    			       			
	    			this._title_tv.setGravity(Gravity.START);
	    			this._title_tv.setTextColor(Color.parseColor("#2a2b2b"));
	    			this._title_tv.setTextSize(UIManager.getInstance().FontSize14);    
	    			this._title_tv.setVisibility(View.GONE);
	    			left.addView(this._title_tv,new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	    		}
	    		
	    		tip_body = new LinearLayout(this._context);
	    		if(null!=tip_body)
	    		{
	    			tip_body.setOrientation(LinearLayout.HORIZONTAL);
	    			
	    			this._speed_tv = new TextView(this._context);
	        		if(null!=this._speed_tv)
	        		{
	        			this._speed_tv.setTextSize(UIManager.getInstance().FontSize8);
	        			this._speed_tv.setTextColor(Color.GRAY);
	        			tip_body.addView(this._speed_tv,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	        		}
	        		
	    			this._progress_tv = new TextView(this._context);
	        		if(null!=this._progress_tv)
	        		{
	        			this._progress_tv.setTextSize(UIManager.getInstance().FontSize8);
	        			this._progress_tv.setTextColor(Color.GRAY);
	        			this._progress_tv.setSingleLine();
	        			tip_body.addView(this._progress_tv,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
	        		}
	        		
	    			left.addView(tip_body,new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
	    		}
        		
        		this._probar = new LProgressView(this._context);
    			if(null!=this._probar)
    			{
    				params = new LayoutParams(LayoutParams.MATCH_PARENT, (int)(4*this._density));
        			if(null!=params)
        			{
        				this._probar.setLayoutParams(params);
        			}
        			this._probar.setFilletRadius(2);
        			left.addView(this._probar);
    			} 
    			
    			this.addView(left);
    		}
    		right = new LinearLayout(this._context);
    		if(null!=right)
    		{
    			right.setOrientation(LinearLayout.HORIZONTAL);
    			right.setGravity(Gravity.CENTER_VERTICAL);
    			
    			this._delbtn_body = new LinearLayout(this._context);
    			if(null!=this._delbtn_body)
    			{ 				
    				this._delbtn_body.setGravity(Gravity.CENTER);
    				this._delbtn_body.setVisibility(View.GONE);
    				delbtn_iv = new ImageView(this._context);
	    			if(null!=delbtn_iv)
	    			{	    				
	    				delbtn_iv.setImageResource(R.drawable.longrise_delete);//ldownloadfileprogressview_del
	    				this._delbtn_body.addView(delbtn_iv);
	    			}
	    			
	    			right.addView(this._delbtn_body,new LayoutParams((int)(36*this._density), (int)(30*this._density)));
    			}
    			
    			this._btn_body = new LinearLayout(this._context);
        		if(null!=this._btn_body)
        		{
        			this._btn_body.setId(k+1);
        			this._btn_body.setGravity(Gravity.CENTER);
        			this._btn_body.setBackgroundColor(Color.parseColor("#6ecc5c"));
        			
				    this._btn = new TextView(this._context);
				    if(null!=this._btn)
				    {
				    	this._btn.setTextColor(Color.WHITE);
				    	this._btn.setText("下载");
				    	this._btn.setGravity(Gravity.CENTER);
				    	this._btn.setSingleLine();
				    	this._btn.setTextSize(UIManager.getInstance().FontSize12);
				    	this._btn_body.addView(this._btn);
				    }
        			
        			right.addView(this._btn_body,new LayoutParams((int)(46*this._density), (int)(26*this._density)));
        		}
    			
    			this.addView(right,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
    		}
    		
    		
    		this.regEvent(true);
    		LDBHelper.createTable(this._context, LDownloadFileProgressViewTable.class);
    	}
    	catch(Exception ex){}
    	finally
    	{
    		delbtn_iv = null;
    		left = null;
    		right = null;
    		tip_body = null;
    		params = null;
    		tip_body = null;
    	}
    }
   
    public void setEnable(boolean enable)
    {
    	this._enable = enable;
    }
    
    public int getRunningStatus()
    {
    	return LDownloadFileProgressManager.getInstance().getStatus(this);
    }
    
    
    public void setButtomVisibility(int visibility)
    {
    	if(null!=this._btn_body)
    	{
    		this._btn_body.setVisibility(visibility);
    	}
    }
    /**
     * 是否画边框（默认为 false）
     */
    public void setDrawBorder(boolean left,boolean top,boolean right,boolean bottom)
    {
    	this._isShowBorderLeft = left;
    	this._isShowBorderTop = top;
    	this._isShowBorderRight = right;
    	this._isShowBorderBottom = bottom;
    }
    /**
     * 设置画进度线方式---------------------------
     * @param type
     */
    public void setPregressBarType(PregressBarType type)
    {
    	
    }
    /**
     * 边框颜色
     * @param color
     */
    public void setBorderColor(int color)
    {
    	this._borderColor = color;
    }
    /**
     * 进度条颜色
     * @param color
     */
    public void setProgressBarColor(int color)
    {
    	if(null!=this._probar)
    	{
    		this._probar.setColor(color);
    	}
    }
    
    public void setProgressBarBackgroundColor(int color)
    {
    	if(null!=this._probar)
    	{
    		this._probar.setBackgroundColor(color);
    	}
    }
    
    public void setProgressVisibility(int visibility)
    {
    	if(null!=this._progress_tv)
    	{
    		this._progress_tv.setVisibility(visibility);
    	}
    }
    
    public void setSpeedVisibility(int visibility)
    {
    	if(null!=this._speed_tv)
    	{
    		this._speed_tv.setVisibility(visibility);
    	}
    }
    
    public void setEllipsize(TruncateAt where)
    {
    	if(null!=this._title_tv)
    	{
			this._title_tv.setEllipsize(where);
    	}
    }    
    public void setSingleLine(boolean singleLine)
    {
    	if(null!=this._title_tv)
    	{
    		this._title_tv.setSingleLine(singleLine);
    	}
    }
    
    public void setTitleTextColor(int color)
    {
    	if(null!=this._title_tv)
    	{
    		this._title_tv.setTextColor(color);
    	}
    }
    
    public void setTitleTextSize(float size)
    {
    	if(null!=this._title_tv)
    	{
    		this._title_tv.setTextSize(size);
    	}
    }
    
    public void setButtonTextColor(int color)
    {
    	if(null!=this._btn)
    	{
    		this._btn.setTextColor(color);
    	}
    }
    
    public void setButtonTextSize(float size)
    {
    	if(null!=this._btn)
    	{
    		this._btn.setTextSize(size);
    	}
    }
   
    
    
    /**
     * 文件打开方式
     * @param type
     */
    public void setOpenType(LFileOpenType type)
    {
    	this._opentype = type;
    }
    
    /**
     * 打开模式
     * @param mode
     */
    public void setOpenModle(LFileOpenMode mode)
    {
    	this._openMode = mode;
    }
    
    /*
     * 设置文件打开回调监听
     */
    public void setOnLDownloadFileProgressViewOpenFileListener(OnLDownloadFileProgressViewOpenFileListener listener)
    {
    	this._openfileLinstener = listener;
    }
    /*
     * 设置文件下载完成回调监听
     */
    public void setOnLDownloadFileProgressViewDownloadFinishListener(OnLDownloadFileProgressViewDownloadFinishListener listener)
    {
    	this._downFinishListener = listener;
    }
    
    public void setOnLDownloadFileProgressViewDownloadErrorListener(OnLDownloadFileProgressViewDownloadErrorListener listener)
    {
    	this._downErrorListener = listener;
    }
    
    /*
    * 设置点击开始下载按钮回调监听
    */
    public void setOnLDownloadFileProgressViewStartListener(OnLDownloadFileProgressViewStartListener listener)
    {
    	this._startLinstener = listener;
    }
    
    /**
     * 设置删除监听
     * @param listener
     */
    public void setOnLDownloadFileProgressViewDeleteListener(OnLDownloadFileProgressViewDeleteListener listener)
    {
    	this._deleteLinstener = listener;
    }
    /**
     * 设置文件标题
     * @param text
     */
    public void setTitle(String text)
    {
    	try
    	{
	    	if(null==text || "".equals(text))return;
	    	if(null!=this._title_tv)
	    	{
	    		this._title_tv.setText(text);
	    		this._title_tv.setVisibility(View.VISIBLE);
	    	}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		text = null;
    	}
    }
    /**
     * 设置文件下载的url路径
     * @param url
     */
    public void setUrl(String url)
    {
    	try
    	{
    		if(null!=url && !"".equals(url))
    		{
    			this._url = URLDecoder.decode(url.trim(),"utf-8");
    		}
    		else
    		{
    			this._url = null;
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		url = null;
    	}
    }
    
    public void setUrl(String url, boolean isDecoder)
    {
    	try
    	{
    		if(null!=url && !"".equals(url))
    		{
    			this._url = isDecoder?URLDecoder.decode(url.trim(),"utf-8"):url;
    		}
    		else
    		{
    			this._url = null;
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		url = null;
    	}
    }
    
    /**
     * 设置文件存放目录
     * @param path
     */
    public void setFileDir(String path)
    {
    	File f = null;
    	try
    	{
    		if(null!=path && !"".equals(path))
    		{
    			f = new File(path);
    			if(null!=f)
    			{
    				if(!f.exists())
    				{
    					f.mkdirs();
    				}
    			}
    			this._filepath = path;
    		}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		f = null;
    		path = null;
    	}
    }
    /**
     * 设置文件名
     * @param name
     */
    public void setFileName(String name)
    {
    	this._filename = name;
    }
    
    public void setProgressHandler(LDownloadFileProgressHandler handler)
    {
    	this._handler = handler;
    }
    
    public void setOutputStream(OutputStream stream)
    {
    	this._outputStream = stream;
    }
    
   /**
    * 获取文件是否被修改
    * @return ：true(被修改)，false(未被修改)
    */
    public boolean getFileChange()
    {
    	File f = null;
    	QueryBuilder<LDownloadFileProgressViewTable,?> query = null;
    	List<LDownloadFileProgressViewTable> list = null;
		try
		{			
			if(null==this._filepath || "".equals(this._filepath))return false;
			if(null==this._filename || "".equals(this._filename))return false;
			if(null==this._url || "".equals(this._url))return false;	
			
			f = new File(this._filepath+this._filename);
			if(null!=f && f.exists())
			{
				query = LDBHelper.getQueryBuilder(this._context, LDownloadFileProgressViewTable.class);
				if(null!=query)
				{
					query.where().eq("filepath", this._filepath+this._filename).and().eq("url", this._url);						
					list = LDBHelper.query(this._context, LDownloadFileProgressViewTable.class, query.prepare());
					if(null!=list && 0<list.size())
					{
						if(f.lastModified() != list.get(0).getLastmodify())
						{
							return true;
						}			
					}
				}
			}
			
			
		}
		catch(Exception ex){}
		finally
		{
			query = null;
			list = null;
			f = null;
		}
    	return false;
    }
    
    /**
     * 当上传成功后，调用此方法
     */
    public void setLastModified()
    {
    	File f = null;
    	QueryBuilder<LDownloadFileProgressViewTable,?> query = null;
    	List<LDownloadFileProgressViewTable> list = null;
		try
		{			
			if(null==this._filepath || "".equals(this._filepath))return;
			if(null==this._filename || "".equals(this._filename))return;
			if(null==this._url || "".equals(this._url))return;	
			
			f = new File(this._filepath+this._filename);
			if(null!=f && f.exists())
			{
				query = LDBHelper.getQueryBuilder(this._context, LDownloadFileProgressViewTable.class);
				if(null!=query)
				{
					query.where().eq("filepath", this._filepath+this._filename).and().eq("url", this._url);						
					list = LDBHelper.query(this._context, LDownloadFileProgressViewTable.class, query.prepare());
					if(null!=list && 0<list.size())
					{
						if(f.lastModified() != list.get(0).getLastmodify())
						{
							list.get(0).setLastmodify(f.lastModified());
							LDBHelper.update(this._context, LDownloadFileProgressViewTable.class, list.get(0));
						}			
					}
				}
			}
			
			
		}
		catch(Exception ex){}
		finally
		{
			query = null;
			list = null;
			f = null;
		}
    }
    /**
     * 删除文件
     */
    public void removeFile()
    {
    	DeleteBuilder<LDownloadFileProgressViewTable, ?> db = null;
    	File file = null;
    	File refile = null;
    	try
    	{
    		if(null==this._filepath || "".equals(this._filepath))return;
    		if(null==this._filename || "".equals(this._filename))return;
    		if(null==this._url || "".equals(this._url))return;
    		
    		db = LDBHelper.getDeleteBuilder(this._context, LDownloadFileProgressViewTable.class);
    		if(null!=db)
    		{
    			db.where().eq("filepath", this._filepath+this._filename).and().eq("url", this._url);
    			LDBHelper.delete(this._context,LDownloadFileProgressViewTable.class,db.prepare());
    		}
    		
    		file = new File(this._filepath+this._filename);
			if(null!=file && file.exists() && file.isFile())
			{
				refile = new File(file.getAbsoluteFile()+".remove");
				if(null!=refile)
				{
					if(file.renameTo(refile))
					{
						refile.delete();
					}
				}
			}
    	}
    	catch(Exception ex){}
    	finally
    	{
    		refile = null;
    		file = null;
    		db = null;
    	}
    }
    
    public void OnDestroy()
    {
    	this.stop();
    	this.regEvent(false);
    	this._delbtn_body = null;
    	this._probar = null;
    	this._filename = null;
      	this._filepath = null;
       	this._opentype = null;
        this._openMode = null;
        this._openfileLinstener = null;
    	this._url = null;
    	this._title_tv = null;
    	this._speed_tv = null;
    	this._progress_tv = null;
    	this._btn = null;
    	this._btn_body = null;
    	this._context = null;
    	this._mPaint = null;
    }
	public LDownloadFileProgressView(Context context) 
	{
		super(context);
		this._context = context;
		this.init();
	}

	
	@Override
	protected void onDraw(Canvas canvas) 
	{
		Rect rect = null;
		
		try
		{
			
			//画边框
			
			if(this._isShowBorderLeft)
			{
				if(null==this._mPaint)
	    		{
	    			this._mPaint = new Paint();
	    		}
				if(null!=this._mPaint)
				{
					this._mPaint.setColor(this._borderColor);	
					canvas.drawLine(0, 0, 0, this.getHeight(), this._mPaint);//left
				}
			}
			if(this._isShowBorderTop)
			{
				if(null==this._mPaint)
	    		{
	    			this._mPaint = new Paint();
	    		}
				if(null!=this._mPaint)
				{
					this._mPaint.setColor(this._borderColor);	
					canvas.drawLine(0, 0, this.getWidth(), 0, this._mPaint);//top
				}
			}
			if(this._isShowBorderRight)
			{
				if(null==this._mPaint)
	    		{
	    			this._mPaint = new Paint();
	    		}
				if(null!=this._mPaint)
				{
					this._mPaint.setColor(this._borderColor);	
					canvas.drawLine(this.getWidth()-1, 0, this.getWidth()-1, this.getHeight(), this._mPaint);//right
				}
			}
			if(this._isShowBorderBottom)
			{
				if(null==this._mPaint)
	    		{
	    			this._mPaint = new Paint();
	    		}
				if(null!=this._mPaint)
				{
					this._mPaint.setColor(this._borderColor);	
					canvas.drawLine(0, this.getHeight()-1, this.getWidth()-1, this.getHeight()-1, this._mPaint);//bottom
				}
			}
			
			/*if(this._drawType == PregressBarType.Fill)
			{
				if(0<this._mProgress && null!=this._mPaint)
				{
					this._mPaint.setColor(this._proLineColor);
					this._mPaint.setAntiAlias(true);
					this._mPaint.setAlpha(128);
					this._mPaint.setStrokeWidth(1.0f);
					rect = new Rect();
					if(null!=rect)
					{
						canvas.getClipBounds(rect);
						rect.left += getPaddingLeft();
						rect.top += getPaddingTop();
						rect.right = (rect.left - getPaddingLeft()) + (this._mProgress * getWidth() / 100) - getPaddingRight();
						rect.bottom -= getPaddingBottom();
						canvas.drawRoundRect(new RectF(rect), 0f, 0f, this._mPaint);
					}
				}
			}
			else if(this._drawType == PregressBarType.BaseLine)
			{
				if(0<this._mProgress && null!=this._mPaint)
				{
					this._mPaint.setColor(this._proLineColor);
					this._mPaint.setAntiAlias(true);
					this._mPaint.setAlpha(128);
					this._mPaint.setStrokeWidth(1.0f);
					rect = new Rect();
					if(null!=rect)
					{
						canvas.getClipBounds(rect);
						rect.left += getPaddingLeft();
						rect.top += this.getHeight()-4;//getPaddingTop();
						rect.right = (rect.left - getPaddingLeft()) + (this._mProgress * getWidth() / 100) - getPaddingRight();
						rect.bottom -= getPaddingBottom();
						canvas.drawRoundRect(new RectF(rect), 0f, 0f, this._mPaint);
					}
				}
			}
			else if(this._drawType == PregressBarType.BaseLine2)
			{			
				if(null!=this._probar)
				{
					this._probar.setProgress(this._mProgress);
				}
			}
			else if(this._drawType == PregressBarType.Stroke) //沿边框画线
	        {
	            this._mPaint.setAntiAlias(true);
	            this._mPaint.setColor(this._proLineColor);
	            this._mPaint.setAlpha(255);
	            rect = new Rect();
	            canvas.getClipBounds(rect);
	            Paint paint1, paint2, paint3, paint4;
	            if(this._mProgress >= 0 && this._mProgress < 25) 
	            {
	                paint1 = new Paint(this._mPaint);
	                Rect temp = new Rect(rect.left + getPaddingLeft(),
	                        rect.top + getPaddingTop(),
	                        rect.left + this._mProgress * (getWidth() - getPaddingLeft() - getPaddingRight())
	                                / 25 - getPaddingRight(),
	                        rect.top + getPaddingTop() + 2);
	                canvas.drawRect(temp, paint1);
	            }
	            else if(this._mProgress < 50) 
	            {
	                paint1 = new Paint(this._mPaint);
	                Rect rect1 = new Rect(rect.left + getPaddingLeft(),
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.top + getPaddingTop() + 2);
	                canvas.drawRect(rect1, paint1);
	
	                paint2 = new Paint(this._mPaint);
	                Rect rect2 = new Rect(rect.right - getPaddingRight() - 2,
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.top + getPaddingTop() + (this._mProgress - 25) *
	                                (getHeight() - getPaddingTop() - getPaddingBottom()) / 25);
	                canvas.drawRect(rect2, paint2);
	            }
	            else if(this._mProgress < 75)
	            {
	                paint1 = new Paint(this._mPaint);
	                Rect rect1 = new Rect(rect.left + getPaddingLeft(),
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.top + getPaddingTop() + 2);
	                canvas.drawRect(rect1, paint1);
	
	                paint2 = new Paint(this._mPaint);
	                Rect rect2 = new Rect(rect.right - getPaddingRight() - 2,
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.bottom - getPaddingBottom());
	                canvas.drawRect(rect2, paint2);
	
	                paint3 = new Paint(this._mPaint);
	                Rect rect3 = new Rect(
	                        rect.right - getPaddingRight() - (this._mProgress - 50) *
	                                (getWidth() - getPaddingLeft() - getPaddingRight()) / 25,
	                        rect.bottom - getPaddingBottom() - 2,
	                        rect.right - getPaddingRight(),
	                        rect.bottom - getPaddingBottom());
	                canvas.drawRect(rect3, paint3);
	            } 
	            else if(this._mProgress <= 100) 
	            {
	                paint1 = new Paint(this._mPaint);
	                Rect rect1 = new Rect(
	                        rect.left + getPaddingLeft(),
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.top + getPaddingTop() + 2);
	                canvas.drawRect(rect1, paint1);
	
	                paint2 = new Paint(this._mPaint);
	                Rect rect2 = new Rect(
	                        rect.right - getPaddingRight() - 2,
	                        rect.top + getPaddingTop(), rect.right - getPaddingRight(),
	                        rect.bottom - getPaddingBottom());
	                canvas.drawRect(rect2, paint2);
	
	                paint3 = new Paint(this._mPaint);
	                Rect rect3 = new Rect(
	                        rect.left + getPaddingLeft(),
	                        rect.bottom - getPaddingBottom() - 2, rect.right - getPaddingRight(),
	                        rect.bottom - getPaddingRight());
	                canvas.drawRect(rect3, paint3);
	
	                paint4 = new Paint(this._mPaint);
	                Rect rect4 = new Rect(
	                        rect.left + getPaddingLeft(),
	                        rect.bottom - getPaddingBottom() - (this._mProgress - 75) *
	                                (getHeight() - getPaddingTop() - getPaddingBottom()) / 25,
	                        rect.left + getPaddingLeft() + 2,
	                        rect.bottom - getPaddingBottom());
	                canvas.drawRect(rect4, paint4);
	            }
	        }*/
			 
			super.onDraw(canvas);
			
			
		}
		catch(Exception ex){}
		finally
		{
			canvas = null;
			rect = null;
		}
		
		
	}
	
	@Override
	public void onClick(View v) 
	{
		int state = -1;
		try
		{
			if(null==v)return;
			if(this._delbtn_body == v)
			{
				LDownloadFileProgressManager.getInstance().stopTask(this, 6);
			}
			else
			{
				state = LDownloadFileProgressManager.getInstance().getStatus(this);				
				if(4==state) //0:可以启动;1:正在下载中；2：已经完成 ;3:下载失败;4:等待下载;5:暂停:6:删除
				{					
					LDownloadFileProgressManager.getInstance().stopTask(this,0);						
				}
				else if(0==state || 3==state || 5==state || 6==state)
				{
					this.start();
				}
				else if(1==state)
				{
					LDownloadFileProgressManager.getInstance().stopTask(this,0);
				}
				else if(2==state)
				{
					this.openfile();
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			v = null;
		}
	}

	
	
	public enum LFileOpenType
	{
		Default,Wps,Never
	}
	
	public enum LFileOpenMode
	{
		Normal,ReadMode,ReadOnly
	}
	public enum PregressBarType
	{
		Fill,Stroke,BaseLine,BaseLine2
	}
	
	public interface OnLDownloadFileProgressViewOpenFileListener
	{
		public void onLDownloadFileProgressViewOpenFile(View v, String filepath);
	}
	public interface OnLDownloadFileProgressViewDownloadFinishListener
	{
		public void onLDownloadFileProgressViewDownloadFinish(View v, String filepath);
	}
	public interface OnLDownloadFileProgressViewDownloadErrorListener
	{
		public void onLDownloadFileProgressViewDownloadError(View v, String filepath);
	}
	public interface OnLDownloadFileProgressViewStartListener
	{
		public void onLDownloadFileProgressViewStart(View v, String filepath);
	}
	
	public interface OnLDownloadFileProgressViewDeleteListener
	{
		public void onLDownloadFileProgressViewDelete();
	}
	
	private Intent getWpsFileIntent(File file,String OpenMode)
	{
		Intent intent = null;
		Bundle bundle = null;
		Uri uri = null;
		try
		{
			if(null==file)return null;
			if(file.exists())
			{
				intent = new Intent();
				if(null!=intent)
				{
					 bundle = new Bundle();
					 if(null!=bundle)
					 {
						 bundle.putString("OpenMode", OpenMode);		//"Normal"
		                 //bundle.putBoolean("SendSaveBroad", true);	//接收不到保存广播
		                 //bundle.putBoolean("SendCloseBroad", true);
		                 //bundle.putString("ThirdPackage", "com.longrise.android.file.wps");//关闭广播会带上此项
		                 bundle.putBoolean("ClearBuffer", true);							//是否清空临时文件
		                 bundle.putBoolean("ClearTrace", true);								//是否删除使用记录
		                 //bundle.putBoolean(ClearFile, true);								//是否删除打开的文件
		                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		                 intent.setAction(Intent.ACTION_VIEW);
		                 intent.setClassName("cn.wps.moffice_eng", "cn.wps.moffice.documentmanager.PreStartActivity2");
		                 
		                 uri = Uri.fromFile(file);
		                 if(null!=uri)
		                 {
		                	 intent.setData(uri);
		                     intent.putExtras(bundle);
		                     return intent;
		                 }
					 }
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			intent = null;
			bundle = null;
			file = null;
			uri = null;
		}
		return null;
	}
	
	private Intent getIntent(File file)
	{
		Intent intent = null;
		try
		{
			if(null!=file)
			{
				if(file.exists())
				{
					
					
					// 取得扩展名
					String end = file.getName().substring(
							file.getName().lastIndexOf(".") + 1, file.getName().length());
					/* 依扩展名的类型决定MimeType */
					if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
							|| end.equals("xmf") || end.equals("ogg") || end.equals("wav"))
					{
						return getAudioFileIntent(file);
					}
					else if (end.equals("3gp") || end.equals("mp4"))
					{
						return getAudioFileIntent(file);
					}
					else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
							|| end.equals("jpeg") || end.equals("bmp"))
					{
						return getImageFileIntent(file);
					}
					else if (end.equals("apk"))
					{
						return getApkFileIntent(file);
					}
					else if (end.equals("ppt") || end.equals("pptx"))
					{						
						return getPptFileIntent(file);
					}
					else if (end.equals("xls") || end.equals("xlsx"))
					{
						return getExcelFileIntent(file);
					}
					else if (end.equals("doc") || end.equals("docx"))
					{
						return getWordFileIntent(file);
					}
					else if (end.equals("pdf"))
					{											
						return getPdfFileIntent(file);
					}
					else if (end.equals("chm"))
					{
						return getChmFileIntent(file);
					}
					else if (end.equals("txt"))
					{
						return getTextFileIntent(file);
					}
					else
					{
						return getAllIntent(file);
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			intent = null;
			file = null;
		}
		return null;
	}
	// Android获取一个用于打开APK文件的intent
	private Intent getAllIntent(File file)
	{

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(file);
		intent.setDataAndType(uri, "*/*");
		return intent;
	}

	// Android获取一个用于打开APK文件的intent
	private Intent getApkFileIntent(File file)
	{

		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(Intent.ACTION_VIEW);
		Uri uri = Uri.fromFile(file);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		return intent;
	}

	// Android获取一个用于打开VIDEO文件的intent
	private Intent getVideoFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("oneshot", 0);
					intent.putExtra("configchange", 0);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "video/*");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装播放器软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
		
	}

	// Android获取一个用于打开AUDIO文件的intent
	private Intent getAudioFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					intent.putExtra("oneshot", 0);
					intent.putExtra("configchange", 0);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "audio/*");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装播放软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}

	// Android获取一个用于打开图片文件的intent
	private Intent getImageFileIntent(File file)
	{

		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "image/*");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装图片浏览软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}

	// Android获取一个用于打开PPT文件的intent
	private Intent getPptFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装PPT支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}
	
	// Android获取一个用于打开Excel文件的intent
	private Intent getExcelFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/vnd.ms-excel");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装Excel支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
		
	}

	// Android获取一个用于打开Word文件的intent
	private Intent getWordFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/msword");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装Word支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}

	// Android获取一个用于打开CHM文件的intent
	private Intent getChmFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/x-chm");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装chm支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
		
	}

	// Android获取一个用于打开文本文件的intent
	private Intent getTextFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "text/plain");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装text支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}

	
	/**
	 * 专用于E人E本T7
	 * @param file
	 * @return
	 */
	private Intent getEbenPdfFileIntent(File file)
	{
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent();
				if(null!=intent)
				{
					intent.setAction(Intent.ACTION_VIEW);
					intent.addCategory(Intent.CATEGORY_DEFAULT);
					intent.putExtra("IS_OA",true);
					intent.setClassName("com.ebensz.pdf.droid", 	"com.ebensz.pdf.droid.pdfsign.droid.PdfViewerActivity");
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/pdf");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装E人E本PDF支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}
	// Android获取一个用于打开PDF文件的intent
	private Intent getPdfFileIntent(File file)
	{		
		Intent intent = null;
		Uri uri = null;
		try
		{
			if(null!=file)
			{
				intent = new Intent("android.intent.action.VIEW");
				if(null!=intent)
				{
					intent.addCategory("android.intent.category.DEFAULT");
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					uri = Uri.fromFile(file);
					if(null!=uri)
					{
						intent.setDataAndType(uri, "application/pdf");
						if(this.isIntentAvailable(intent))
						{
							return intent;
						}
						else
						{
							if(null!=this._context)
							{
								Toast.makeText(this._context, "未能识别的文件，请安装PDF支持软件", Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			file = null;
			intent = null;
			uri = null;
		}
		return null;
	}
	
	private boolean isIntentAvailable(Intent intent) 
	{ 
		PackageManager packageManager = null;
		List<ResolveInfo> list = null;
		try
		{
			if(null!=this._context)
			{
				packageManager = this._context.getPackageManager(); 
				if(null!=packageManager)
				{
					list = packageManager.queryIntentActivities(intent, PackageManager.GET_ACTIVITIES);
					if(null!=list)
					{
						return list.size() > 0; 
					}
				}
			}
		}
		catch(Exception ex){}
		finally
		{
			intent = null;
			packageManager = null;
			list = null;
		}
        return false;
	 }

	
}
